class ProjectController < ApplicationController
#  require 'rubygems'
#  require 'RMagick'
#  include Magick
#  before_filter :login_required
#  permit "admin_project of Project"

  def index
     @projects=Project.find(:all)
     flash.now[:project_index]="project number:#{@projects.length}"
  end

  def new
    @project=Project.new
    @project_snapshot=ProjectSnapshot.new
  end

  def create
    @project=Project.new(params[:project])
    @project_snapshot=ProjectSnapshot.new(:uploaded_data=>params[:uploaded_data])
    project_service=ProjectService.new(@project,@project_snapshot)
    if project_service.save
       flash[:create]='Project has been created'
       redirect_to(projects_url,:method=>:get)
    else
      #can not use the route
      render(:action=>:new)
    end
  end

  def edit
    @project=Project.find_by_id(params[:id])
  end
 #FIXME how updating the blank image input work and destroying the exist images work ?
  def update
     @project=Project.find_by_id(params[:id])
     @project_snapshot=@project.project_snapshot
     project_service=ProjectService.new(@project,@project_snapshot)
     if project_service.update(params[:project],params[:uploaded_data])
       flash[:update]='Project has been updated'
       redirect_to(projects_url,:method=>:get)
     else
       #redefine the variables to get error
       @project=project_service.project
       @project_snapshot=project_service.project_snapshot
      render(:action=>:edit)
     end
  end

  def delete
    if request.delete?
     project=Project.find_by_id(params[:id])
     #two pages delete the same project at the same time
     project.destroy if project
     flash[:delete_project]="The project has been deleted"
    end
    redirect_to(projects_url)
  end

end
